<template>
  <div>
    <el-drawer
      title="通知配置"
      size="40%"
      :model="false"
      :visible.sync="dialogVisibles"
      :before-close="closeAddDialog"
      :modal-append-to-body="false"
      :close-on-press-escape="false"
      :wrapperClosable="false"
      :destroy-on-close="true"
      :append-to-body="true">
      <el-button type="primary" :disabled="estimate" class="select-template" round @click="templateDialog = true">选择模板
      </el-button>
      <span style="color: red" v-if="estimate">无通知模板可选，请联系管理员前往 "商务中心-全局配置-通知配置" 中进行配置</span>
      <notice-edit v-if="offerTemplateConfLoaded || templateSelected"
                   :configValue="addForm"
                   :showBase="true"
                   :editable="true"
                   :config="true"
                   @submit="submit"
                   @close="closeAddDialog">
      </notice-edit>
    </el-drawer>

    <!-- 选择模板弹窗 -->
    <el-dialog
      title="选择模板"
      :visible.sync="templateDialog"
      width="80%"
      :before-close="handleClose"
      :modal-append-to-body="false"
      :close-on-click-modal="true"
      :append-to-body="true">
      <div v-if="templateDialog">
        <avue-crud ref="multipleTable"
                   v-model="form"
                   :data="data"
                   :option="option"
                   :page.sync="page"
                   :search.sync="search"
                   :table-loading="loading"
                   @search-change="searchChange"
                   @search-reset="searchReset"
                   @current-change="currentChange"
                   @size-change="sizeChange"
                   @refresh-change="refreshChange"
                   @on-load="onLoad"
                   @selection-change="selectionChange">
          <template slot-scope="{type,size,row}" slot="menu">
            <el-button icon="el-icon-view" :size="size" :type="type" @click="checkRow(row)">查 看</el-button>
          </template>
        </avue-crud>
      </div>

      <div style="display: flex;justify-content: center;">
        <el-button type="primary" size="medium " @click="saveTemplateData">确定</el-button>
        <el-button size="medium " @click="handleClose">取消</el-button>
      </div>

    </el-dialog>

    <el-drawer
      title="查看通知模版"
      size="40%"
      :visible.sync="checkTemplate"
      :before-close="closeDialog"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      :wrapperClosable="false"
      :append-to-body="true">
      <notice-edit :configValue="checkData"
                   :showBase="true"
                   :editable="false"
                   :config="false"
                   @submit="submit"
                   @close="closeDialog">
      </notice-edit>

    </el-drawer>

    <!--    <check-template :checkRow=checkTemplate :checkData=checkData @closeDialog="closeDialog"></check-template>-->

  </div>
</template>

<script>
import {
  checkNoticeTemplate,
  checkOfferNotice,
  getPage,
  getTemplateInfom,
  selectInformGroup
} from "@/api/business/thirdpartyconf";
import {getList} from "@/api/system/role";
import {getOfferConf, saveOfferConf} from "@/api/business/offer";
import {mapGetters} from "vuex";
import func from '@/util/func'
import CheckTemplate from "@/views/system/components/checkComponent/checkTemplate";
import NoticeEdit from "@/views/system/notice/noticeEdit";
import {refineObject} from "@/util/util";

export default {
  name: "templateConf",
  components: {
    CheckTemplate,
    NoticeEdit
  },
  props: {
    dialogVisible: {
      type: Boolean
    },
    offerID: {
      type: String
    },
    globalConf: {
      type: Array
    },
    globalSwitch: {
      type: String| Number
    }
  },
  computed: {
    ...mapGetters(["offer"]),
  },
  data() {
    let verifyOfferGroup = (rule, value, callback) => {
      if (!value && (this.addForm.createStatusAlter === 100 || this.addForm.offerEdit === 100 || this.addForm.offerConflict === 100)) {
        callback(new Error('请选择通知群'));
      }
      callback();
    }
    let verifyGroup = (rule, value, callback) => {
      if (!value && this.addForm.requestCommunicate === 100) {
        callback(new Error('请选择通知群'));
      }
      callback();
    }
    let verifyAuditGroup = (rule, value, callback) => {
      if (!value && this.addForm.creativeAudit === 100) {
        callback(new Error('请选择通知群'));
      }
      callback();
    }
    return {
      dialogVisibles:this.dialogVisible,
      requestSwitchDemand: false,
      requestSelectDisabled: false,
      auditSwitchDemand: false,
      auditSelectDisabled: false,
      estimate: false,
      checkTemplate: false,
      checkData: {},
      selectionList: {},
      loading: false,
      query: {},
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      search: {},
      form: {},
      data: [],
      option: {
        select: true,
        tip: false,
        selection: true,
        searchMenuSpan: 6,
        refreshBtn: false,
        columnBtn: false,
        addBtn: false,
        editBtn: false,
        delBtn: false,
        viewBtn: false,
        column: [
          {
            label: '序列号',
            prop: 'id'
          },
          {
            label: '模板名称',
            prop: 'name',
            search: true,
          },
          {
            label: '通知方式',
            prop: 'notificeType',
            search: true,
            type: 'select',
            dicData: [
              {label: "飞书群", value: 0},
              {label: "企业微信群", value: 1},
              {label: "飞书个人", value: 2},
              // {label: "企业微信个人", value: 3},
            ]
          }
        ]
      },
      templateDialog: false,
      informGroupList: [],
      informRoleList: [],
      addRules: {
        // name: {required: true, message: '请输入模板名称', trigger: 'change'},
        requestCommunicateNoticeGroup: [{
          required: false, validator: verifyGroup, message: '请选择通知群', trigger: 'change',
        }],
        creativeAuditNoticeGroup: [{
          required: false, validator: verifyAuditGroup, message: '请选择通知群', trigger: 'change',
        }],
        offerNoticeGroup: [{
          required: false, validator: verifyOfferGroup, message: '请选择通知群', trigger: 'change',
        }]
      },
      addForm: {
        // id: '',
        // inProduction: 100,
        // createStatusAlter: 100,
        // offerEdit: 100,
        // offerConflict: 100,
        // requestCommunicate: 100,
        // requestCreate: 100,
        // assignTask: 100,
        // uploadProduct: 100,
        // productConfirm: 100,
        // requestAdd: 100,
        // creativeAudit: 100,
        // auditSubmit: 100,
        // auditResult: 100,
        // requestContentAudit: 100,
        // requestEdit: 100,
        // inProductionNoticeRoles: '',
        // name: '',
        // notificeType: '',
        // offerNotice: '',
        // offerNoticeGroup: '',
        // offerRole: '',
        // offerEditNoticeRoles: '',
        // offerConflictNoticeRoles: '',
        // requestCommunicateNoticeGroup: '',
        // requestCreateNoticeRoles: '',
        // assignTaskNoticeRoles: '',
        // uploadProductNoticeRoles: '',
        // productConfirmNoticeRoles: '',
        // requestAddNoticeRoles: '',
        // creativeAuditNoticeGroup: '',
        // auditSubmitNoticeRoles: '',
        // auditResultNoticeRoles: '',
        // requestContentAuditNoticeRoles: '',
        // requestEditNoticeRoles: '',
        //
        // offerId: '',
        // // offerNoticeRoles: '',
      },
      templateId: '',
      offerTemplateConfLoaded: false,
      templateSelected: false,
      templateData: '',
      allOfferNoticeConf: []

    }
  },
  watch: {
    dialogVisible: {
      deep: true,
      handler(val) {
        this.dialogVisibles=val
        if (val) {
          this.init();
        }
      }
    }
  },
  created() {
    this.init();
  },
  methods: {
    init() {
      getList().then(res => {
        this.informRoleList = res.data.data.records
      })
      if (this.offerID !== '') {
        getOfferConf({offerId: this.offerID}).then(res => {
          let offerNoticeConf = res.data.data;
          if (offerNoticeConf) {
            if (offerNoticeConf.id) {
              this.offerTemplateConfLoaded = true;
              for (let key in offerNoticeConf) {
                this.addForm[key] = offerNoticeConf[key];
                if (key == 'requestContentAudit') {
                  let obj = this.addForm;
                }
              }
              //this.addForm = Object.assign({},offerNoticeConf,this.addForm);
              // let data = {
              //   createStatusAlterNoticeRoles: func.toList(this.addForm.createStatusAlterNoticeRoles),
              //   offerEditNoticeRoles: func.toList(this.addForm.offerEditNoticeRoles),
              //   offerConflictNoticeRoles: func.toList(this.addForm.offerConflictNoticeRoles),
              //   requestCreateNoticeRoles: func.toList(this.addForm.requestCreateNoticeRoles),
              //   assignTaskNoticeRoles: func.toList(this.addForm.assignTaskNoticeRoles),
              //   uploadProductNoticeRoles: func.toList(this.addForm.uploadProductNoticeRoles),
              //   productConfirmNoticeRoles: func.toList(this.addForm.productConfirmNoticeRoles),
              //   requestAddNoticeRoles: func.toList(this.addForm.requestAddNoticeRoles),
              //   auditSubmitNoticeRoles: func.toList(this.addForm.auditSubmitNoticeRoles),
              //   auditResultNoticeRoles: func.toList(this.addForm.auditResultNoticeRoles),
              //   requestContentAuditNoticeRoles: func.toList(this.addForm.requestContentAuditNoticeRoles),
              //   requestEditNoticeRoles: func.toList(this.addForm.requestEditNoticeRoles),
              //   inProductionNoticeRoles: func.toList(this.addForm.inProductionNoticeRoles),
              //   // offerNoticeRoles: func.toList(this.addForm.offerNoticeRoles),
              // }
              // Object.assign(this.addForm, data)
              // this.getInformGroup(this.addForm.notificeType);
              // this.desired()
              // this.createReview()
            }
            checkNoticeTemplate().then(res => {
              this.templateData = res.data.data
              if (this.templateData === "不存在") {
                this.estimate = true
              }
            })
          }
        });
      }
    },
    // //需求沟通全局开关
    // desired() {
    //   if (this.addForm.requestCommunicate === 100) {
    //     this.addForm.requestCreate = 100
    //     this.addForm.assignTask = 100
    //     this.addForm.uploadProduct = 100
    //     this.addForm.productConfirm = 100
    //     this.addForm.requestAdd = 100
    //     this.addForm.requestContentAudit = 100
    //     this.addForm.requestEdit = 100
    //     this.addForm.inProduction = 100,
    //       this.requestSwitchDemand = false
    //     this.requestSelectDisabled = false
    //   }
    //   if (this.addForm.requestCommunicate === 0) {
    //     this.addForm.requestCreate = 0
    //     this.addForm.assignTask = 0
    //     this.addForm.uploadProduct = 0
    //     this.addForm.productConfirm = 0
    //     this.addForm.requestAdd = 0
    //     this.addForm.requestContentAudit = 0
    //     this.addForm.requestEdit = 0
    //     this.addForm.inProduction = 0
    //     this.requestSwitchDemand = true
    //     this.requestSelectDisabled = true
    //   }
    //
    // },
    // //素材审核全局开关
    // createReview() {
    //   if (this.addForm.creativeAudit === 100) {
    //     this.addForm.auditResult = 100
    //     this.addForm.auditSubmit = 100
    //     this.auditSelectDisabled = false
    //     this.auditSwitchDemand = false
    //   } else {
    //     this.addForm.auditResult = 0
    //     this.addForm.auditSubmit = 0
    //     this.auditSelectDisabled = true
    //     this.auditSwitchDemand = true
    //   }
    // },
    //接收checkTemplate子组件的值
    closeDialog() {
      this.checkTemplate = false
    },
    /*查看函数*/
    checkRow(row) {
      getTemplateInfom(row.id).then(res => {
        this.checkData = res.data.data;
        this.checkTemplate = true
      })
    },
    /*保存函数*/
    submit(data) {
      data.templateConfId = this.templateId;
      data.offerId = this.offerID;
      saveOfferConf(data).then((res) => {
        if (res.data.success) {
          this.$message.success("通知配置保存成功");
          this.$emit('allNotice')
        } else {
          this.$message.error("通知配置保存失败");
        }
      }).finally(() => {
        this.closeAddDialog();
      });
    },
    /*获取->选择通知方式群函数*/
    // changeInformGroup(notificeType) {
    //   this.addForm.offerNoticeGroup = '';
    //   this.addForm.requestCommunicateNoticeGroup = '';
    //   this.addForm.creativeAuditNoticeGroup = '';
    //   this.getInformGroup(notificeType);
    // },
    // getInformGroup(parameter) {
    //   selectInformGroup(parameter).then(res => {
    //     this.informGroupList = res.data.data
    //   })
    // },
    /*回到第一页方法*/
    homepage() {
      this.page = {
        pageSize: 10,
        currentPage: 1,
        total: 0
      }
      this.refreshChange()
    },
    /*确定选择模板方法*/
    saveTemplateData() {
      if (!this.selectionList.name) {
        this.$message({
          type: "warning",
          message: '您没有选择任何模板'
        })
        this.templateDialog = false;
        this.homepage()
        return
      }
      // this.addForm = refineObject(this.addForm, [{from: -1, to: 0}]);
      // this.selectionList = refineObject(this.selectionList, [{from: -1, to: 0}]);
      // this.addForm = Object.assign(this.addForm, this.selectionList);

      this.selectionList = refineObject(this.selectionList, [{from: -1, to: 0}]);
      let data = refineObject(this.addForm, [{from: -1, to: 0}]);
      data = Object.assign(data, this.selectionList);
      data.offerId = this.offerID;
      data.id = '';
      this.addForm = Object.assign({}, data);
      this.templateId = this.selectionList.id
      // let data = {
      //   offerRole: func.toList(this.addForm.offerRole),
      //   createStatusAlterNoticeRoles: func.toList(this.addForm.createStatusAlterNoticeRoles),
      //   offerEditNoticeRoles: func.toList(this.addForm.offerEditNoticeRoles),
      //   offerConflictNoticeRoles: func.toList(this.addForm.offerConflictNoticeRoles),
      //   requestCreateNoticeRoles: func.toList(this.addForm.requestCreateNoticeRoles),
      //   assignTaskNoticeRoles: func.toList(this.addForm.assignTaskNoticeRoles),
      //   uploadProductNoticeRoles: func.toList(this.addForm.uploadProductNoticeRoles),
      //   productConfirmNoticeRoles: func.toList(this.addForm.productConfirmNoticeRoles),
      //   requestAddNoticeRoles: func.toList(this.addForm.requestAddNoticeRoles),
      //   auditSubmitNoticeRoles: func.toList(this.addForm.auditSubmitNoticeRoles),
      //   auditResultNoticeRoles: func.toList(this.addForm.auditResultNoticeRoles),
      //   requestContentAuditNoticeRoles: func.toList(this.addForm.requestContentAuditNoticeRoles),
      //   requestEditNoticeRoles: func.toList(this.addForm.requestEditNoticeRoles),
      //   inProductionNoticeRoles: func.toList(this.addForm.inProductionNoticeRoles),
      // }
      // Object.assign(this.addForm, data)

      // selectInformGroup(this.addForm.notificeType).then(res => {
      //   this.informGroupList = res.data.data
      // })

      // this.addForm.offerId = this.offerID;
      this.templateDialog = false;
      this.templateSelected = true;
      // this.requestSelectDisabled = this.addForm.requestCommunicate !== 100;
      // this.auditSelectDisabled = this.addForm.creativeAudit !== 100;
      this.homepage()
    },
    /*实现单选方法*/
    selectionChange(selection) {
      if (selection.length > 1) {
        const preVal = selection.shift();
        this.$refs.multipleTable.toggleRowSelection(preVal, false);
      }
      this.selectionList = selection[0]
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = false;
      getPage(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const dataList = res.data.data
        this.page.total = dataList.total
        this.data = dataList.records;
        // this.selectionClear();
      })
    },
    /*选择模板弹窗回调关闭*/
    handleClose() {
      this.page = {
        pageSize: 10,
        currentPage: 1,
        total: 0
      }
      this.refreshChange()
      this.templateDialog = false
    },
    /*通知配置弹窗回调关闭*/
    closeAddDialog() {
      this.$emit('closeAddDialog')
      this.offerTemplateConfLoaded = false;
      this.templateSelected = false;
      if (this.$refs.addForm)
        this.$refs.addForm.resetFields();
      this.dialogVisibles = false;
      this.addCheck = false;
    },
  }
}
</script>

<style scoped lang="scss">
/deep/ .el-drawer.rtl {
  overflow: scroll;
}

.form_item {
  padding-left: 10px;
}

.switch_item {
  margin-bottom: 1em;
  display: flex;
  align-items: center;

  .switch {
    padding: 0 20px;
  }

  .switch_label {
    margin-right: 20px;
  }

  .Sub_option {
    margin-left: 5em;
  }
}

.delete_icon {

}

.offer-status-alter {
  margin-top: 20px;
  margin-left: 25px
}

.select-template {
  margin-left: 120px;
  width: 200px;
  margin-bottom: 20px;
}

/deep/ .el-form-item__error {
  margin-top: -15px !important;
  margin-left: 215px !important;
}
</style>
